package cn.edu.cqupt.service.impl;

import cn.edu.cqupt.dao.OwnerDao;
import cn.edu.cqupt.dao.RelatedFileDao;
import cn.edu.cqupt.dao.RoomDao;
import cn.edu.cqupt.po.CheckInInfo;
import cn.edu.cqupt.po.ForRoom;
import cn.edu.cqupt.po.Owner;
import cn.edu.cqupt.po.RelatedFile;
import cn.edu.cqupt.po.Room;
import cn.edu.cqupt.po.RoomInfoList;
import cn.edu.cqupt.service.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Andrew
 * @date 2018/5/26
 */
@Service
public class OwnerServiceImpl implements OwnerService{

    @Autowired
    OwnerDao ownerDao;
    @Autowired
    RoomDao roomDao;
    @Autowired
    RelatedFileDao relatedFileDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean checkIn(CheckInInfo checkInInfo) {
        Owner owner = checkInInfo.getOwner();
        ownerDao.insert(owner);
        Room room = checkInInfo.getRoom();
        room.setOwnerId(owner.getId());
        roomDao.insert(room);
        Integer roomId = room.getId();
        checkInInfo.getRelatedFileList().stream().forEach(r ->{
            r.setRoomId(roomId);
            relatedFileDao.insert(r);
        });
        return true;
    }

    @Override
    public Room getRoom(Integer roomId) {
        return roomDao.select(roomId);
    }

    @Override
    public boolean saveRoom(Room room) {
        int count = roomDao.update(room);
        return count == 1;
    }

    @Override
    public Owner getOwner(Integer ownerId) {
        return ownerDao.select(ownerId);
    }

    @Override
    public boolean saveOwner(Owner owner) {
        int count = ownerDao.update(owner);
        return count == 1;
    }

    @Override
    public List<RelatedFile> getRoomFiles(Integer roomId) {
        return relatedFileDao.selectByRoomId(roomId);
    }

    @Override
    public List<RoomInfoList> getAllInfo(ForRoom forRoom) {
        return roomDao.selectAllInfo(forRoom);
    }
}
